import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '../api'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const classes = ref([])
  const courses = ref([])
  const grades = ref([])

  // 设置加载状态
  const setLoading = (value) => {
    loading.value = value
  }

  // 获取班级列表
  const fetchClasses = async () => {
    try {
      loading.value = true
      const response = await api.get('/classes')
      classes.value = response.data
    } catch (error) {
      console.error('获取班级列表失败:', error)
      // 如果API失败，使用备用数据
      classes.value = [
        { id: 1, name: '计算机科学与技术1班', grade: '2023', student_count: 30 },
        { id: 2, name: '计算机科学与技术2班', grade: '2023', student_count: 28 },
        { id: 3, name: '软件工程1班', grade: '2023', student_count: 25 },
        { id: 4, name: '软件工程2班', grade: '2023', student_count: 27 },
        { id: 5, name: '网络工程班', grade: '2023', student_count: 22 }
      ]
    } finally {
      loading.value = false
    }
  }

  // 获取课程列表
  const fetchCourses = async () => {
    try {
      loading.value = true
      const response = await api.get('/courses')
      courses.value = response.data
    } catch (error) {
      console.error('获取课程列表失败:', error)
      // 如果API失败，使用备用数据
      courses.value = [
        { id: 1, name: '高等数学', code: 'MATH101', credits: 4, teacher: '张教授' },
        { id: 2, name: '程序设计基础', code: 'CS101', credits: 3, teacher: '李老师' },
        { id: 3, name: '数据结构', code: 'CS201', credits: 3, teacher: '王老师' },
        { id: 4, name: '数据库原理', code: 'CS301', credits: 3, teacher: '刘教授' },
        { id: 5, name: '计算机网络', code: 'CS302', credits: 3, teacher: '陈老师' }
      ]
    } finally {
      loading.value = false
    }
  }

  // 获取成绩统计
  const fetchGrades = async () => {
    grades.value = [
      { course: '高等数学', average: 78.5, pass_rate: 85 },
      { course: '程序设计基础', average: 82.3, pass_rate: 92 },
      { course: '数据结构', average: 75.8, pass_rate: 78 },
      { course: '数据库原理', average: 80.1, pass_rate: 88 },
      { course: '计算机网络', average: 77.9, pass_rate: 82 }
    ]
  }

  return {
    loading,
    classes,
    courses,
    grades,
    setLoading,
    fetchClasses,
    fetchCourses,
    fetchGrades
  }
}) 